import { ElMessage } from 'element-plus'
import { createRouter, createWebHistory } from 'vue-router'
import { projectName } from '../../config/config.default'

const routes = [
  {
    path: '/',
    name: '/',
    component: () => import('../views/login.vue'),
    meta: {
      title: '登录',
    },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue'),
    meta: {
      title: '404',
    },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue'),
    meta: {
      title: '登陆',
    },
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue'),
    meta: {
      title: '注册',
    },
  },
  { path: '/:pathMatch(.*)*', redirect: '/404' }, // 结尾的 * 表示匹配任意深度路径，若没有对应路由页面则跳转至404

  // 前台路由
  {
    path: '/front',
    name: 'front',
    component: () => import('../views/front.vue'),
    children: [
      // 前台子路由
      {
        path: 'home',
        name: 'frontHome',
        component: () => import('../views/front/home.vue'),
        meta: {
          title: '前台首页',
        },
      },
    ],
  },

  // 后台路由
  {
    path: '/back',
    name: 'back',
    component: () => import('../views/back.vue'),
    children: [
      // 后台子路由
      {
        path: 'home',
        name: 'backHome',
        component: () => import('../views/back/home.vue'),
        meta: {
          title: '后台首页',
        },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 全局前置守卫
const whitePath = ['/login', '/register', '/404']
router.beforeEach((to, from, next) => {
  const account = JSON.parse(localStorage.getItem('account') || '{}')
  if (to.matched.length === 0) {
    next('/404')
    return
  }
  if (whitePath.includes(to.path)) {
    // 如果是登陆或者注册，直接放行
    next()
    return
  }
  if (!account.role) {
    // 未登陆，跳转至登陆页
    next('/login')
    ElMessage.error('请先登陆')
    return
  }
  if (to.path === '/') {
    // 访问根路径
    if (account.role === 'ROLE_ADMIN') {
      next('/back/home')
    } else {
      next('/front/home')
    }
  } else {
    next()
  }
})

// 全局后置守卫
router.afterEach(to => {
  document.title = to.meta.title
    ? `${to.meta.title} - ${projectName}`
    : projectName // 设置页面标题
})

export default router
